#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  build.py
#  
#  Copyright 2013 Wang Sen <wangsen@linux.vnet.ibm.com>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.

from config import config
from myrepo import myrepo
from base import base
from util import ssh_cmd
import util
import os

class rpm_build(base):
	def __init__(self, repo_obj):
		super(rpm_build, self).__init__()
		self._repoobj = repo_obj
		self._build_path = self._conf.get_build('build_path')
		self._build_script = self._build_path + '/build_virt.sh'
		self._spec_path = self._conf.get('gitdir') + '/' + self._repoobj._name \
						  + '/' + self._repoobj._name + '.spec'
		self._user = self._conf.get_build('koji_user')
		self._host = self._conf.get_build('koji_host')
		self._testres = 'error' # succ or error
	def do_test_build(self):
		if self._repoobj.valid:
			# call a script on koji server to do the build
			# fix me need to copy build_virsh.sh
			copy_spec_cmd = 'scp %s %s@%s:%s' % (self._spec_path, self._user, \
					self._host, self._build_path)
			cmd = self._build_script + ' -t ' + ' -n ' + self._repoobj.name \
				  + ' -r ' + self._conf.get_build('cur_release') + ' -s ' + \
				  self._conf.get_build('cur_update') + ' -f ' + \
				  self._build_path + '/' + self._repoobj._name + '.spec'
			ssh_cmds = 'ssh -t  %s@%s \"%s\"' % (self._user, self._host, cmd)
			if self._repoobj.is_pushed:
				self.logger.debug(copy_spec_cmd)
				(r, o, e) = util.exec_command(copy_spec_cmd)
				if r != 0:
					self.logger.debug("copy spec file [%s] failed" % \
							self._repoobj.name)
					return False
				self.logger.debug(ssh_cmds)
				(rc, out, err) = util.exec_command(ssh_cmds)
				if rc == 0:
					self.logger.info("build ok [%s]" % self._repoobj.name)
					self._repoobj.status = 'success'
				else:
					self.logger.error("build failed [%s]" % self._repoobj.name)
					self._repoobj.status = out
